package cn.tiger.controller;

import cn.tiger.common.CodeMsg;
import cn.tiger.common.Result;
import cn.tiger.pojo.dto.AskQuestionRequest;
import cn.tiger.pojo.dto.CreateConversationRequest;
import cn.tiger.pojo.vo.AskQuestionResponse;
import cn.tiger.pojo.vo.ConversationVO;
import cn.tiger.pojo.vo.MessageVO;
import cn.tiger.service.ConversationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;

/**
 * 对话控制器
 * 
 * 提供AI问答对话相关的REST API接口，包括对话创建、问答、历史查询等功能
 * 集成阿里云通义千问Qwen-Plus模型，提供智能对话体验
 * 
 * @author AI Backend Team
 * @version 1.0
 * @since 2025-09-26
 */
@Slf4j // 启用Lombok日志功能
@RestController // REST控制器注解
@RequestMapping("/api/conversation") // API基础路径
@RequiredArgsConstructor // Lombok注解，生成构造函数
@Validated // 参数校验
@Tag(name = "对话管理", description = "AI问答对话相关接口") // Swagger文档标签
public class ConversationController {
    
    /** 
     * 对话服务层依赖注入
     * 提供对话管理、AI问答等业务逻辑处理
     */
    private final ConversationService conversationService;
    
    /**
     * 创建新对话
     * @param request 创建对话请求
     * @param httpRequest HTTP请求对象，用于获取用户信息
     * @return 对话ID
     */
    @Operation(summary = "创建新对话", description = "创建一个新的AI问答对话")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "创建成功"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @PostMapping("/create")
    public Result<Long> createConversation(@Valid @RequestBody CreateConversationRequest request, HttpServletRequest httpRequest) {
        // 从JWT token中获取用户ID
        Long userId = (Long) httpRequest.getAttribute("userId");
        request.setUserId(userId);
        
        Long conversationId = conversationService.createConversation(request);
        return Result.success("创建对话成功", conversationId);
    }
    
    /**
     * 提问并获取AI回答
     * @param request 提问请求
     * @return 提问响应
     */
    @Operation(summary = "提问并获取AI回答", description = "向AI提问并获取回答，支持创建新对话或在现有对话中继续")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "提问成功"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @PostMapping("/ask")
    public Result<AskQuestionResponse> askQuestion(@Valid @RequestBody AskQuestionRequest request, HttpServletRequest httpRequest) {
        // 从JWT token中获取用户ID
        Long userId = (Long) httpRequest.getAttribute("userId");
        request.setUserId(userId);
        
        AskQuestionResponse response = conversationService.askQuestion(request);
        return Result.success("提问成功", response);
    }

    /**
     * 获取用户的对话列表
     * @param httpRequest 用户ID
     * @return 对话列表
     */
    @Operation(summary = "获取用户对话列表", description = "获取指定用户的所有对话列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @GetMapping("/list")
    public Result<List<ConversationVO>> getUserConversations(HttpServletRequest httpRequest) {
        // 从JWT token中获取用户ID
        Long userId = (Long) httpRequest.getAttribute("userId");
        
        List<ConversationVO> conversations = conversationService.getUserConversations(userId);
        return Result.success("获取对话列表成功", conversations);
    }
    
    /**
     * 获取对话详情
     * @param conversationId 对话ID
     * @param userId 用户ID
     * @return 对话详情
     */
    @Operation(summary = "获取对话详情", description = "获取指定对话的详细信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "对话不存在"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @GetMapping("/detail/{conversationId}")
    public Result<ConversationVO> getConversationDetail(
            @Parameter(description = "对话ID", required = true) @PathVariable Long conversationId,
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId) {
        ConversationVO conversation = conversationService.getConversationDetail(conversationId, userId);
        if (conversation == null) {
            return Result.error(new CodeMsg(404, "对话不存在"));
        }
        return Result.success("获取对话详情成功", conversation);
    }
    
    /**
     * 获取对话中的消息列表
     * @param conversationId 对话ID
     * @return 消息列表
     */
    @Operation(summary = "获取对话消息列表", description = "获取指定对话中的所有消息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @GetMapping("/messages/{conversationId}")
    public Result<List<MessageVO>> getConversationMessages(
            @Parameter(description = "对话ID", required = true) @PathVariable Long conversationId) {
        List<MessageVO> messages = conversationService.getConversationMessages(conversationId);
        return Result.success("获取消息列表成功", messages);
    }
    
    /**
     * 删除对话
     * @param conversationId 对话ID
     * @param userId 用户ID
     * @return 删除结果
     */
    @Operation(summary = "删除对话", description = "删除指定的对话")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "对话不存在"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @DeleteMapping("/{conversationId}")
    public Result<Boolean> deleteConversation(
            @Parameter(description = "对话ID", required = true) @PathVariable Long conversationId,
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId) {
        boolean success = conversationService.deleteConversation(conversationId, userId);
        if (success) {
            return Result.success("删除对话成功", true);
        } else {
            return Result.error(new CodeMsg(404, "对话不存在"));
        }
    }
    
    /**
     * 获取对话中的剩余提问次数
     * @param conversationId 对话ID
     * @param httpRequest HTTP请求对象，用于获取用户信息
     * @return 剩余提问次数
     */
    @Operation(summary = "获取剩余提问次数", description = "获取指定对话中用户的剩余提问次数")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "对话不存在"),
            @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @GetMapping("/remaining-questions/{conversationId}")
    public Result<Integer> getRemainingQuestions(
            @Parameter(description = "对话ID", required = true) @PathVariable Long conversationId,
            HttpServletRequest httpRequest) {
        // 从 JWT token 中获取用户ID
        Long userId = (Long) httpRequest.getAttribute("userId");
        
        // 验证对话是否存在且属于该用户
        ConversationVO conversation = conversationService.getConversationDetail(conversationId, userId);
        if (conversation == null) {
            return Result.error(new CodeMsg(404, "对话不存在"));
        }
        
        // 获取当前对话中用户发送的消息数量
        long userMessageCount = conversationService.getUserMessageCount(conversationId);
        
        // 计算剩余提问次数
        int remainingQuestions = conversationService.getRemainingQuestions(userId, userMessageCount);
        
        return Result.success("获取成功", remainingQuestions);
    }
}